import 'package:dio/dio.dart';

class AuthInterceptor extends Interceptor {
  final Future<String?> Function() getToken;
  final Future<String?> Function() refreshToken;

  AuthInterceptor({
    required this.getToken,
    required this.refreshToken,
  });

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    // 自动添加 token
    final token = await getToken();
    if (token != null && token.isNotEmpty) {
      options.headers['Authorization'] = 'Bearer $token';
    }
    handler.next(options);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    // Token 过期处理 (401)
    if (err.response?.statusCode == 401) {
      final newToken = await refreshToken();
      if (newToken != null && newToken.isNotEmpty) {
        // 更新请求头并重试
        err.requestOptions.headers['Authorization'] = 'Bearer $newToken';
        try {
          final response = await Dio().fetch(err.requestOptions);
          return handler.resolve(response);
        } catch (retryError) {
          return handler.next(err);
        }
      }
    }
    handler.next(err);
  }
}